<?php
namespace frame\libs;

use frame\libs\Config;
use frame\libs\Session;
use app\admin\model\LogModel;

/**
 * 日志类
 */
class Log {

    /**
     * 创建静态私有的变量保存该类对象
     * @var [type]
     */
    private static $instance;

    /**
     * 防止使用new直接创建对象
     */
    private function __construct() {}

    /**
     * 防止使用clone克隆对象
     * @return [type] [description]
     */
    private function __clone() {}

    /**
     * 单例，判断$instance是否是Singleton的对象，不是则创建
     * @return [type] [description]
     */
    public static function init()
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 创建文件
     * @return [type] [description]
     */
    public function create()
    {
        $dir = ROOT_PATH . Config::get('path', 'log') . DS . date("Ym", time()) . DS;
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
        $file = $dir . date("Ymd", time()) . ".log";
        if (!is_file($file)) {
            touch($file);
        }
        return $file;
    }

    /**
     * 日志内容
     * @param  string $username [description]
     * @param  string $data     [description]
     * @return [type]           [description]
     */
    public function write()
    {
        return array(
            'time' => date("Y-m-d H:i:s", time()),
            'ip' => $_SERVER['REMOTE_ADDR'],
            'url' => $_SERVER['REQUEST_URI'],
            'data' => isset($_POST) ?  json_encode($_POST) : array(),
            'user' => Session::get('username') ? Session::get('username') : 'null',
        );
    }

    /**
     * 保存日志
     * @param  string $username [description]
     * @param  string $data     [description]
     * @return [type]           [description]
     */
    public function save()
    {
        $mothed = Config::get('drive', 'log');
        $this->$mothed();
    }

    /**
     * 文件方式保存日志
     * @param  string $username [description]
     * @return [type]           [description]
     */
    public function file()
    {
        $data = $this->write();
        $msg = "[".$data['time']."], ip: ".$data['ip'].", user: ".$data['user'].", access: ".$data['url'].", data: ".$data['data'].";\n\n";
        file_put_contents($this->create(), $msg, FILE_APPEND);
    }

    /**
     * 数据库方式保存日志
     * @param  string $username [description]
     * @return [type]           [description]
     */
    public function mysql()
    {
        LogModel::getInstance()->insertLog($this->write());
    }

}

